package storage

import (
	"gitee.com/alex_li/zangjingge/internal/db/rdb"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/app-starter/server"
	"net/http"
)

type DocResp struct {
	Code     string `json:"code,omitempty"`
	Name     string `json:"name,omitempty"`
	Bucket   string `json:"bucket,omitempty"`
	FilePath string `json:"filePath,omitempty"`
	Digest   string `json:"digest,omitempty"`
	FileSize int64  `json:"fileSize,omitempty"`
}

func docList(ctx server.Context) {

	var err error
	var resp app.ResponseWrapper
	pageNo := ctx.C.URLParamIntDefault("page", 1)
	pageSize := ctx.C.URLParamIntDefault("size", 50)
	bucket := ctx.C.URLParamDefault("bucket", "")

	var simplePager app.SimplePager[rdb.DocInfo, DocResp]
	simplePager.PageSize = pageSize
	simplePager.PageNum = pageNo
	simplePager.Transform = func(src rdb.DocInfo, dst *DocResp) {
		dst.Code = src.Code
		dst.Name = src.Name
		dst.Bucket = src.Bucket
		dst.FilePath = src.FilePath
		dst.FileSize = src.FileSize
		dst.Digest = src.Digest
	}
	simplePager.QueryBuilder = func(tx persistence.TxContext) any {
		return tx.Context.QueryTable(new(rdb.DocInfo)).Filter("bucket", bucket)
	}
	err = app.QueryPage(&simplePager)
	if err != nil {
		resp.Code = http.StatusInternalServerError
		resp.Message = err.Error()
		ctx.Json(resp)
		return
	}

	resp.Data = simplePager.Pager
	resp.Code = http.StatusOK
	ctx.Json(resp)
}
